<template>
    <div>
        <el-card style="height: 80px;">
            <el-form :inline="true" size="normal" class="form">
                <el-form-item label="职位搜索" style="width: 300px;">
                    <el-input placeholder="请你输入搜索职位关键字" v-model="keyword"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search" :disabled="keyword ? false : true">搜索</el-button>
                    <el-button type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>

        </el-card>
        <el-card style="margin-top: 10px;">
            <el-button type="primary" size="default" @click="addRole" icon="Plus">添加职位</el-button>
            <el-table border style="margin: 10px 0px;" :data="allRole">
                <el-table-column label="#" type="index" width="50px" align="center">
                </el-table-column>
                <el-table-column label="ID" width="300px" align="center" prop="id">
                </el-table-column>
                <el-table-column label="职位名称" width="300px" align="center" prop="roleName">
                </el-table-column>
                <el-table-column label="创建时间" width="300px" align="center" prop="createTime">
                </el-table-column>
                <el-table-column label="更新时间" width="300px" align="center" prop="updateTime">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" icon="User" @click="setPermisstion(row)">分配权限</el-button>
                        <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
                        <el-popconfirm :title="`你确定要删除${row.roleName}吗?`" @confirm="removeRole(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete" @click="">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
                :background="true" layout="prev, pager, next, jumper,->, sizes,total" :total="total"
                @size-change="sizeChange" @current-change="getHasRole" />
        </el-card>
        <!-- 对话框 -->
        <el-dialog v-model="dialogVisible" :title="RoleParams.id ? '更新职位' : '添加职位'" width="800px">
            <el-form :model="RoleParams" :rules="rules" ref="form">
                <el-form-item label="职位名称" prop="roleName">
                    <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="save">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 抽屉 -->
        <el-drawer v-model="drawer">
            <template #header>
                <h4>分配菜单与按钮的权限</h4>
            </template>
            <template #default>
                <!-- 树形控件 -->
                <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
                    :default-checked-keys="selectArr" :props="defaultProps" />
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer = false">取消</el-button>
                    <el-button type="primary" @click="handler">确定</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue';
import { reqAddOrUpdateRole, reqAllMenuList, reqAllRoleList, reqRemoverRole, reqSetPermisstion } from '@/api/acl/role';
import { onMounted } from 'vue';
import { RoleResponseData, RoleData, Records, MenuResponseData, MenuList } from '@/api/acl/role/type';
import { ElMessage } from 'element-plus';
import useLayOutSettingStrore from '@/store/modules/setting';
let pageNo = ref<number>(1);
let pageSize = ref<number>(5);
let total = ref<number>(0);
let keyword = ref<string>('');
// 储存所有角色数据
let allRole = ref<Records>([]);
// 收集新增职位数据
let RoleParams = reactive<RoleData>({
    roleName: ''
})
let dialogVisible = ref(false);
let form = ref<any>();
//获取模板setting仓库
let settingStore = useLayOutSettingStrore();
// 控制抽屉
let drawer = ref<Boolean>(false);
// 收集全部按钮权限数据
let menuArr = ref<MenuList>([]);
// 收集角色有的权限
let selectArr = ref<number[]>([]);
//获取tree组件实例
let tree = ref<any>();
//树形控件的测试数据
const defaultProps = {
    children: 'children',
    label: 'name',
}

onMounted(() => {
    getHasRole()
})

// 获取所有角色数据
const getHasRole = async (pager = 1) => {
    //修改当前页码
    pageNo.value = pager;
    let result: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value);
    if (result.code == 200) {
        total.value = result.data.total;
        allRole.value = result.data.records;
    }

}
const sizeChange = () => {
    getHasRole();
}
// 搜索角色的回调函数
const search = () => {
    getHasRole();
}
// 重置按钮的回调函数
const reset = () => {
    settingStore.refsh = !settingStore.refsh;
}
// 添加角色的回调函数
const addRole = () => {
    dialogVisible.value = true;
    // 清空数据
    Object.assign(RoleParams, {
        roleName: '',
        id: 0
    });
    // 清空错误信息
    nextTick(() => {
        form.value.clearValidate()
    })

}
//自定义校验规则的回调
const validatorRoleName = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack();
    } else {
        callBack(new Error('职位名称至少两位'))
    }
}
//职位校验规则
const rules = {
    roleName: [
        { required: true, trigger: 'blur', validator: validatorRoleName }
    ]
}
// 对话框确定按钮的回调函数
const save = async () => {
    // 表单校验
    await form.value.validate();
    dialogVisible.value = false;
    let result: any = await reqAddOrUpdateRole(RoleParams);
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: RoleParams.id ? '修改成功' : '添加成功'
        });
        // 再次获取全部职位,更新留在当前页面,添加回到第一页
        getHasRole(RoleParams.id ? pageNo.value : 1);
    }
}
// 编辑按钮的回调函数
const updateRole = (row: RoleData) => {
    dialogVisible.value = true
    // 收集数据
    Object.assign(RoleParams, row);
    // 清空错误信息
    nextTick(() => {
        form.value.clearValidate();
    })
}
// 分配权限按钮的回调函数
const setPermisstion = async (row: RoleData) => {
    drawer.value = true;
    // 收集当前要分类权限的职位的数据
    Object.assign(RoleParams, row)
    let result: MenuResponseData = await reqAllMenuList((RoleParams.id as number));
    if (result.code == 200) {
        menuArr.value = result.data;
        selectArr.value = filterSelectArr(menuArr.value, [])
    }


}
// 过滤数组,只过滤叶子节点
const filterSelectArr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        // lever是下拉菜单层级
        if (item.select && item.level == 4) {
            initArr.push(item.id)
        }
        //    有children进入循环,直到level==4,判断是否push到initArr
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr);
        }
    })

    return initArr;
}
// 树形控件确定按钮的回调函数
const handler = async () => {
    const roleId = (RoleParams.id as number);
    // 节点被全部选中的权限
    let arr = tree.value.getCheckedKeys();
    // 节点没有被全部选中的权限
    let arr1 = tree.value.getHalfCheckedKeys();
    let permissionId = arr.concat(arr1);
    console.log(arr1);
    console.log(arr);
    console.log(permissionId);
    let result: any = await reqSetPermisstion(roleId, permissionId);
    if (result.code) {
        drawer.value = false;
        ElMessage({ type: 'success', message: '分配权限成功' })
        // 页面刷新
        window.location.reload();
    }
}
// 删除按钮的回调函数
const removeRole = async (roleId: number) => {
    let result: any = await reqRemoverRole(roleId);
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }
}
</script>

<style scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>